package com.jxb.seven;

/**
 * 示例 1：
 * 输入：nums = [1,1,1,1,1], target = 3
 * 输出：5
 * 解释：一共有 5 种方法让最终目标和为 3 。
 * -1 + 1 + 1 + 1 + 1 = 3
 * +1 - 1 + 1 + 1 + 1 = 3
 * +1 + 1 - 1 + 1 + 1 = 3
 * +1 + 1 + 1 - 1 + 1 = 3
 * +1 + 1 + 1 + 1 - 1 = 3
 *
 * 状态转移公式：dp[j] = dp[j] + dp[j-nums[i]]
 * 初始化：dp[0] = 1
 */
public class TargetSum_494 {

    public int findTargetSumWays(int[] nums, int target) {
        int n = nums.length;
        //提前剪枝
        if (n == 1) {
            return nums[0] == target || nums[0] == -target ? 1:0;
        }
        //统计数组元素和
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        //总和没有target多，返回0
        //总和-目标值 为奇数，返回0
        //  nums = [1,1,1,1,1,1], target = 3,sum - target = 3,奇数题目本身无解
        int diff = sum - target;
        if (diff < 0 || diff%2 != 0) {
            return 0;
        }
        int need = diff/2;
        //dp数组
        //nums = [1,1,1,1,1], target = 3
        //[1,0,0]
        //环形数组
        int[] dp = new int[need + 1];
        dp[0] = 1;
        for (int num : nums) {
            for (int j = need;j>=num;j--) {
                dp[j] = dp[j] + dp[j-num];
            }
        }
        return dp[need];

    }

    public static void main(String[] args) {
        System.out.println(5/2);
    }



}
